<?php

class comments extends Module {
	
	public function __construct () {
		parent::__construct (__CLASS__);
		
		$this->extend ('__custom_comments');
	}
	
	public function __default() {
		$this->setPageTitle(lang('header_live',__CLASS__));
		
		$response = $this->getCommentsList();
		$response->setTemplate('comments/index');
		
		return $response;
	}
	
	public function getcomments ($sTypeName = false, $objectId = false) {
		$typesController = TypesController::getInstance ();
		$objectsController = ObjectsController::getInstance ();
		
		$oCommentType = $typesController->getTypeByName ('comment');
		
		$sel = new Selection;
		$sel->addType ($oCommentType);
		$sel->setOrder ('pubdate');
		
		if ($sTypeName === false && getRequest ('param0') != '') {
			$sTypeName = getRequest ('param0');
		}
		if ($objectId === false && getRequest ('param1', 'int') != 0) {
			$objectId = getRequest ('param1', 'int');
		}
		
		if ($sTypeName !== false) {
			if ($oType = $typesController->getTypeByName ($sTypeName)) {
				$sel->addFilter ('type_id', $oType->getId ());
			}
		}
		if ($objectId !== false) {
			$sel->addFilter ('object_id', $objectId);
		}
		
		$aObjects = $objectsController->getObjectsList ($sel->getList ());
		
		$aRelatedList = array ();
		$aNormalList = array ();
		
		foreach ($aObjects as $object) {
			if (userGroup (ExplaySession::getUser()->getValue ('group')) != 'guest' && ExplaySession::getUserId () != $object->getValue ('owner_id')) {
				$object->setAttribute ('allow-vote', '1');
			} else {
				$object->setAttribute ('allow-vote', '0');
			}
			$aRelatedList[$object->getValue('rel_id')][] = $object;
		}
		
		if (isset ($aRelatedList[0])) {
			$this->detectLevel ($aRelatedList[0], 0, $aRelatedList, $aNormalList);
		}
		
		$response = new ModuleResponse;
		$response->setTemplate (getRequest('reload', 'bool') ? 'comments/showComments' : 'comments/defaultList');
		$response->setAttribute ('type-name', $sTypeName);
		$response->setAttribute ('object-id', $objectId);
		foreach ($aNormalList as $object) {
			$response->addObject ($object);
		}
		
		return $response;
	}
	
	
	
	public function ajax_delete () {
		$this->expectSecureGET();
		
		$id = getRequest ('param0', 'int');
		
		if ($oComment = ObjectsController::getInstance ()->getObject (TypesController::getInstance()->getTypeByName ('comment'), $id)) {
			$oComment->setValue ('deleted', 1);
			$oComment->save ();
			$this->flush ((string) new Array2XML ('data', array ('result' => '1')), 'text/xml');
		}

		$this->flush ((string) new Array2XML ('data', array ('result' => '0')), 'text/xml');
	}
	
	public function ajax_vote () {
		$this->expectSecureGET();
		
		$typesController = TypesController::getInstance ();
		$objectsController = ObjectsController::getInstance ();
		
		$id = getRequest ('param0', 'int');
		$mark = getRequest ('param1', 'int');
		
		$oCommentType = $typesController->getTypeByName ('comment');
				
		if (!$oComment = $objectsController->getObject ($oCommentType, $id)) {
			$this->flush ((string) new Array2XML ('data', array ('result' => '0')), 'text/xml');
		}
		
		$oVoteType = $typesController->getTypeByName ('vote');
		
		$sel = new Selection;
		$sel->addType ($oVoteType);
		$sel->addFilter ('user_id', ExplaySession::getUserId ());
		$sel->addFilter ('object_id', $id);
		$sel->addFilter ('type_id', $oCommentType->getId ());
		
		if ($sel->getTotalCount () > 0) {
			$this->flush ((string) new Array2XML ('data', array ('result' => '0')), 'text/xml');
		}
		
		$oVote = new Object ($oVoteType);
		$oVote->setValues (array (
			'type_id' => $oCommentType->getId (),
			'object_id' => $id,
			'user_id' => ExplaySession::getUserId (),
			'mark' => $mark == 1 ? '1' : '0'
		));
		$oVote->createNew ();
		
		$rating = $oComment->getValue ('rating');
		$rating = $mark == 1 ? ++$rating : --$rating;
		$oComment->setValue ('rating', $rating);
		$oComment->save ();
		
		$format = number_format ($rating, 0, ',', ' ');
		$format = str_replace('-', '−', $format);
		
		$this->flush ((string) new Array2XML ('data', array ('result' => '1', 'rating' => $rating, 'format' => $format)), 'text/xml');
	}
	
	public function user() {
		$objectsController = ObjectsController::getInstance();
		$typesController = TypesController::getInstance();
		
		$oTypeComment = $typesController->getTypeByName('comment');
		
		$userLogin = getRequest('param0');
		
		$oTypeUser = $typesController->getTypeByName('user');
		
		$sel = new Selection;
		$sel->addType($oTypeUser);
		$sel->addFilter('login', $userLogin);
		$sel->addLimit(1);
		
		$res = $sel->getList();

		if (!isset($res[0])) {
			throw new NotFound;
		}
		
		$userId = $res[0][0];
		
		$oUser = $objectsController->getObject($oTypeUser, $userId);
		$this->setPageTitle(lang('header_prefix_user',__CLASS__) . $oUser->getValue('name'));
		
		$response = $this->getCommentsList(
			array('owner_id' => $userId),
			null,
			array(
				'user-login' => $userLogin,
				'user-id' => $userId
			)
		);
		$response->setTemplate('comments/user');
		$response->setAttribute('user-login', $userLogin);
		$response->setAttribute('user-id', $userId);
				
		return $response;
	}
	
	public function getLive($count) {
		$aPages = array ();
		$aPages['page'] = getRequest ('page', 'int');
		if ($aPages['page'] > 0) {
			$aPages['page']--;
		}
		$aPages['onpage'] = (int) $count;
		
		return $this->getCommentsList(null, $aPages);
	}
	
	private function getCommentsList(array $aFilters = null, array $aPages = null, array $aResponseAtributes = null, $orderFieldName = 'pubdate', $ascOrber = false) {
		$typesController = TypesController::getInstance();
		
		$oTypeComment = $typesController->getTypeByName('comment');
		
		$sel = new Selection;
		$sel->addType($oTypeComment);
		
		if ($aFilters !== null) {
			foreach ($aFilters as $fieldName => $filteredValue) {
				if (is_array ($filteredValue)) {
					$sel->addFilter ($fieldName, $filteredValue[0], $filteredValue[1]);
				} else {
					$sel->addFilter ($fieldName, $filteredValue);
				}
			}
		}
		
		$sel->setOrder($orderFieldName, $ascOrber);
		
		if ($aPages === null) {
			$aPages = array ();
			$aPages['page'] = getRequest ('page', 'int');
			if ($aPages['page'] > 0) {
				$aPages['page']--;
			}
			$aPages['onpage'] = (int) Regedit::getInstance()->get ('//modules/comments/user_comments_on_page');
		}
		$sel->addLimit ($aPages['page'] * $aPages['onpage'], $aPages['onpage']);
		
		$aObjects = ObjectsController::getInstance()->getObjectsList($sel->getList());
		
		$response = new ModuleResponse;
		if ($aResponseAtributes !== null) {
			foreach ($aResponseAtributes as $name => $value) {
				$response->setAttribute($name, $value);
			}
		}
		
		
		foreach ($aObjects as $object) {
			$object->setAttribute('type-name', $typesController->getTypeById($object->getValue('type_id'))->getName());
			$response->addObject($object);
		}
		
		$response->addObject (new Array2XML ('pages', array (
			'onpage' => $aPages['onpage'],
			'total' => $sel->getTotalCount (),
			'page' => ++$aPages['page']
		)));
		
		return $response;
	}
	
	private function detectLevel (array &$list, $level, &$aRelatedList, &$aNormalList) {
		foreach ($list as $oComment) {
			$oComment->setAttribute ('comment-level', $level);
			$aNormalList[] = $oComment;
			if (isset ($aRelatedList[$oComment->getId()])) {
				$this->detectLevel ($aRelatedList[$oComment->getId()], $level+1, $aRelatedList, $aNormalList);
			}
		}
	}
	
}